import { Message, MessageBox } from 'element-ui'
import util from '@/libs/util.js'
import router from '@/router'
import api from '@/api'
import { post } from '@/utils/request'
import { adminLoginUrl } from '@/utils/interface'

export default {
  namespaced: true,
  actions: {
    async login ({ dispatch }, {
      username = '',
      password = ''
    } = {}) {
      try {
        const res = await post(adminLoginUrl, { username, password })
        const uuid = res.data.data.uuid
        const token = res.data.data.token
        const name = res.data.data.username
        util.cookies.set('uuid', uuid)
        util.cookies.set('token', token)
        await dispatch('d2admin/user/set', { name: name }, { root: true })
        await dispatch('load')
      } catch (error) {
        console.log('登录失败', error)
        Message.error('登录失败')
      }
    },
    logout ({ commit, dispatch }, { confirm = false } = {}) {
      async function logout () {
        util.cookies.remove('token')
        util.cookies.remove('uuid')
        await dispatch('d2admin/user/set', {}, { root: true })
        router.push({ name: 'login' })
      }
      if (confirm) {
        commit('d2admin/gray/set', true, { root: true })
        MessageBox.confirm('确定要注销当前用户吗', '注销用户', { type: 'warning' })
          .then(() => {
            commit('d2admin/gray/set', false, { root: true })
            logout()
          })
          .catch(() => {
            commit('d2admin/gray/set', false, { root: true })
            Message({ message: '取消注销操作' })
          })
      } else {
        logout()
      }
    },
    async load ({ dispatch }) {

      await dispatch('d2admin/user/load', null, { root: true })
      // 加载主题
      await dispatch('d2admin/theme/load', null, { root: true })
      // 加载页面过渡效果设置
      await dispatch('d2admin/transition/load', null, { root: true })
      // 持久化数据加载上次退出时的多页列表
      await dispatch('d2admin/page/openedLoad', null, { root: true })
      // 持久化数据加载侧边栏配置
      await dispatch('d2admin/menu/asideLoad', null, { root: true })
      // 持久化数据加载全局尺寸
      await dispatch('d2admin/size/load', null, { root: true })
      // 持久化数据加载颜色设置
      await dispatch('d2admin/color/load', null, { root: true })
    }
  }
}
